﻿<div class="page">
    <div id="header" class="bar">
        <div id="btnAddBlog" class="btn-left">
            <span>Add Blog</span>
        </div>
        
        <div id="btnSettings" class="btn-right">
            <span>Settings</span>
        </div>
    </div>
    <div id="content">
        <ul id="blogs">
            
        </ul>
    </div>
</div>
<script language="javascript" type="text/javascript">
    (function () {
        function displayBlogs(blogs) {
            var $blogs = $("#blogs");
            var html = "";
            for (var i = 0; i < blogs.length; i++) {
                var blog = blogs[i];
                html += "<li data-id='" + blog.id + "'><div class='blog-title'>" + blog.title + "</div>";
                html += "<div class='blog-date'>" + blog.lastUpdatedDate + "</div>";
                html += "<div class='blog-content'>" + blog.content + "</div>";
                html += "</li>";
            }
            $blogs.html(html);
        }

        function initPageEvents() {
            $("#content").height($(window).height() - $("#header").height() + "px");
            var scroller = new nova.Scroller("#blogs");
            scroller.init();
            nova.touch.bindClick("#btnSettings", function () {
                nova.application.gotoPage("pages/settings.html");
            });
            nova.touch.bindClick("#btnAddBlog", function () {
                var page = new nova.Page("pages/editTitle.html");
                page.blog = new Blog();
                nova.application.gotoPage(page);
            });
            nova.touch.bindClick("#blogs>li", function () {
                var blogId = $(this).attr("data-id");
                new DbService().getBlog(blogId, function (blog) {
                    var page = new nova.Page("pages/details.html");
                    page.blog = blog;
                    nova.application.gotoPage(page);
                });
            });
        }

        $(document).ready(function () {
            var service = new DbService();
            try {
                service.init(function () {
                    service.getBlogs(function (blogs) {
                        displayBlogs(blogs);
                        initPageEvents();
                    });
                });
            }
            catch (ex) {
                alert(ex);
            }
        });
    })();
</script>